from flask import Flask, render_template, request, jsonify, session, redirect, send_from_directory
from flask_cors import CORS  # pyright: ignore[reportMissingModuleSource]
from werkzeug.utils import secure_filename
import json
import hashlib
import os
import random
from datetime import datetime, timezone, timedelta
import uuid
import requests  # 用于调用DeepSeek AI API

# 设置北京时区 (UTC+8)
beijing_tz = timezone(timedelta(hours=8))

def get_beijing_time():
    """获取北京时间"""
    return datetime.now(beijing_tz)

app = Flask(__name__)

# 设备检测函数
def is_mobile():
    """检测是否为移动设备"""
    user_agent = request.headers.get('User-Agent', '').lower()
    mobile_keywords = ['mobile', 'android', 'iphone', 'ipad', 'ipod', 'blackberry', 'windows phone', 'webos']
    return any(keyword in user_agent for keyword in mobile_keywords)
app.secret_key = 'your-secret-key-change-this-in-production'  # 生产环境请更换为随机字符串

# ========== 文件上传配置 ==========
UPLOAD_FOLDER = 'static/uploads/questions'
AVATAR_UPLOAD_FOLDER = 'static/uploads/avatars'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
MAX_FILE_SIZE = 5 * 1024 * 1024  # 5MB

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_FILE_SIZE

# 确保上传文件夹存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(AVATAR_UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# ===================================

# ========== CORS 跨域配置（微信小程序必需） ==========
# 允许微信小程序访问 API
CORS(app, resources={
    r"/api/*": {
        "origins": "*",  # 生产环境建议指定具体域名
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Content-Type", "Authorization"],
        "supports_credentials": True
    }
})
# ================================================

# ========== MySQL数据库配置区域 ==========
# 如果要使用数据库，请取消下面的注释并安装依赖
# 安装命令：pip install PyMySQL

import pymysql.cursors  # 未使用
import pymysql

# # 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'port': 3306,  # 数据库端口，默认3306
    'user': 'root',
    'password': '123456',  # 请修改为你的MySQL密码
    'database': 'quiz_system',
    'charset': 'utf8mb4'
}

def check_fill_in_answer(user_answer, correct_answer, keywords=''):
    """检查填空题答案是否正确"""
    if not user_answer or not correct_answer:
        return False
    
    # 清理用户答案
    user_answer = user_answer.strip().lower()
    
    # 处理多个正确答案（用逗号分隔）
    correct_answers = [ans.strip().lower() for ans in correct_answer.split(',')]
    
    # 处理关键词（用逗号分隔），确保keywords不为None
    keyword_list = [kw.strip().lower() for kw in (keywords or '').split(',') if kw.strip()]
    
    # 检查是否匹配正确答案
    if user_answer in correct_answers:
        return True
    
    # 检查是否匹配关键词
    if user_answer in keyword_list:
        return True
    
    # 模糊匹配（去除空格、标点符号）
    import re
    user_clean = re.sub(r'[^\w\u4e00-\u9fff]', '', user_answer)
    
    for ans in correct_answers:
        ans_clean = re.sub(r'[^\w\u4e00-\u9fff]', '', ans)
        if user_clean == ans_clean:
            return True
    
    for kw in keyword_list:
        kw_clean = re.sub(r'[^\w\u4e00-\u9fff]', '', kw)
        if user_clean == kw_clean:
            return True
    
    return False

def get_db_connection():
    """获取数据库连接"""
    try:
        return pymysql.connect(**DB_CONFIG)
    except Exception as e:
        print(f"数据库连接失败: {e}")
        return None

USE_DATABASE = True  # 设置为True启用数据库
# USE_DATABASE = False  # 当前使用示例数据
# ========================================

# 管理员密码（生产环境请修改）
ADMIN_PASSWORD = 'admin123'  # 默认管理员密码

# ========== 用户认证系统 ==========
def hash_password(password):
    """加密密码"""
    return hashlib.sha256(password.encode()).hexdigest()

def verify_password(password, hashed):
    """验证密码"""
    return hash_password(password) == hashed

def get_user_from_db(username):
    """从数据库获取用户"""
    if not USE_DATABASE:
        return None
    try:
        conn = get_db_connection()
        if not conn:
            return None
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT id, username, password, email, avatar, score, quiz_count, created_at, updated_at
                FROM users WHERE username = %s
            """, [username])
            user = cursor.fetchone()
        
        conn.close()
        return user
    except Exception as e:
        print(f"[ERROR] 获取用户失败: {e}")
        return None

def create_user_in_db(username, email, password):
    """在数据库中创建用户"""
    if not USE_DATABASE:
        return False
    
    try:
        conn = get_db_connection()
        if not conn:
            return False
        
        hashed_password = hash_password(password)
        created_at = get_beijing_time().strftime('%Y-%m-%d %H:%M:%S')
        
        with conn.cursor() as cursor:
            cursor.execute("""
                INSERT INTO users (username, email, password, score, quiz_count, created_at, updated_at)
                VALUES (%s, %s, %s, 0, 0, %s, %s)
            """, [username, email, hashed_password, created_at, created_at])
        
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"[ERROR] 创建用户失败: {e}")
        return False

def update_user_in_db(username, **kwargs):
    """更新用户信息"""
    if not USE_DATABASE:
        return False
    
    try:
        conn = get_db_connection()
        if not conn:
            return False
        
        # 检查是否要更新username
        update_username = 'username' in kwargs
        new_username = kwargs.pop('username', None) if update_username else None
        
        # 如果没有其他要更新的字段，直接返回
        if not kwargs and not update_username:
            return True
        
        with conn.cursor() as cursor:
            # 如果要更新username，先更新其他字段
            if kwargs:
                update_fields = [f"{key} = %s" for key in kwargs.keys()]
                values = list(kwargs.values())
                values.append(get_beijing_time().strftime('%Y-%m-%d %H:%M:%S'))
                values.append(username)
                
                cursor.execute(f"""
                    UPDATE users SET {', '.join(update_fields)}, updated_at = %s WHERE username = %s
                """, values)
            
            # 如果要更新username，最后更新（避免WHERE条件的问题）
            if update_username and new_username:
                cursor.execute("""
                    UPDATE users SET username = %s, updated_at = %s WHERE username = %s
                """, [new_username, get_beijing_time().strftime('%Y-%m-%d %H:%M:%S'), username])
        
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"[ERROR] 更新用户失败: {e}")
        import traceback
        traceback.print_exc()

        return False
# ========================================


# 添加404错误处理器
@app.errorhandler(404)
def not_found(error):
    if request.path.startswith('/api/'):
        return jsonify({'success': False, 'message': 'API接口不存在'}), 404
    return "页面不存在", 404

@app.route("/")  
def index():
    auth_data = {
        "registerNum": 0,
        "questionNum": 0,
        "answerNum": 0,
    }
    
    try:
        conn = get_db_connection()
        if not conn:
            print("数据库连接失败，使用默认数据")
        else:
            with conn:  # 自动关闭连接（推荐）
                cursor = conn.cursor()
                # 查询注册数
                cursor.execute("SELECT COUNT(*) FROM users")
                auth_data["registerNum"] = cursor.fetchone()[0]  # 获取结果

                # 查询问题数
                cursor.execute("SELECT COUNT(*) FROM questions")
                auth_data["questionNum"] = cursor.fetchone()[0]

                # 查询答题数
                cursor.execute("SELECT COUNT(*) FROM quiz_results")
                auth_data["answerNum"] = cursor.fetchone()[0]

                print(f"注册数: {auth_data['registerNum']}")  # 示例：更清晰的输出
                print(auth_data)  # 如果想打印整个dict
    except Exception as e:
        print(f"数据库操作失败: {e}")  # 更详细的错误信息，便于调试
        # 继续执行，使用默认的auth_data
    
    # 传递用户登录状态给首页
    if is_mobile():
        return render_template("mobile/index.html", logged_in=session.get('logged_in', False), 
                             username=session.get('username', ''),authData=auth_data)
    return render_template("index.html", logged_in=session.get('logged_in', False), 
                         username=session.get('username', ''), authData=auth_data)


@app.route("/login")
def login():
    if is_mobile():
        return render_template("mobile/login.html")
    return render_template("login.html")


@app.route("/register")
def register():
    if is_mobile():
        return render_template("mobile/register.html")
    return render_template("register.html")


@app.route("/admin")
def admin():
    # 检查管理员是否已登录
    if not session.get('admin_logged_in'):
        return redirect('/admin-login')
    return render_template("admin.html")


@app.route("/admin-login")
def admin_login():
    # 如果已经登录，重定向到管理员页面
    if session.get('admin_logged_in'):
        return redirect('/admin')
    return render_template("admin_login.html")

@app.route("/test")
def test_page():
    """Test页面 - 管理tack表"""
    return render_template("test.html")
@app.route("/quiz")
def quiz():
    # 可选的登录检查
    # if not session.get('logged_in'):
    #     return redirect('/login')
    if is_mobile():
        return render_template("mobile/quiz.html", logged_in=session.get('logged_in', False),
                             username=session.get('username', ''))
    return render_template("quiz.html", logged_in=session.get('logged_in', False), 
                         username=session.get('username', ''))


@app.route("/quiz-detail")
def quiz_detail():
    """答题详情页"""
    if is_mobile():
        return render_template("mobile/quiz-detail.html")
    return render_template("quiz-detail.html")


@app.route("/profile")
def profile():
    # 检查登录状态
    if not session.get('logged_in'):
        return redirect('/login')
    if is_mobile():
        return render_template("mobile/profile.html")
    return render_template("profile.html")


@app.route("/leaderboard")
def leaderboard():
    if is_mobile():
        return render_template("mobile/leaderboard.html")
    return render_template("leaderboard.html")


@app.route("/api/get-questions", methods=['GET'])
def get_questions():
    """获取题目列表API - 支持随机选题"""
    category = request.args.get('category', '')
    
    if USE_DATABASE:
        # 使用数据库
        try:
            conn = get_db_connection()
            if not conn:
                return jsonify({'success': False, 'error': '数据库连接失败，请检查数据库配置'})
            
            with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                # 如果有指定分类，查询指定分类的题目
                if category:
                    cursor.execute("""
                        SELECT q.id, q.title, q.question_type, q.question_image, 
                               q.option_a, q.option_a_image, 
                               q.option_b, q.option_b_image, 
                               q.option_c, q.option_c_image, 
                               q.option_d, q.option_d_image, 
                               q.fill_in_answer, q.fill_in_keywords,
                               q.correct_answer, q.explanation, q.explanation_image, 
                               q.difficulty, q.category_id,
                               c.name as category_name
                        FROM questions q
                        INNER JOIN categories c ON q.category_id = c.id
                        WHERE c.name = %s AND q.status = 'active'
                    """, [category])
                else:
                    # 如果没有指定分类，查询所有题目（用于综合答题）
                    cursor.execute("""
                        SELECT q.id, q.title, q.question_type, q.question_image, 
                               q.option_a, q.option_a_image, 
                               q.option_b, q.option_b_image, 
                               q.option_c, q.option_c_image, 
                               q.option_d, q.option_d_image, 
                               q.fill_in_answer, q.fill_in_keywords,
                               q.correct_answer, q.explanation, q.explanation_image, 
                               q.difficulty, q.category_id,
                               c.name as category_name
                        FROM questions q
                        INNER JOIN categories c ON q.category_id = c.id
                        WHERE q.status = 'active'
                    """)
                
                all_questions = cursor.fetchall()
                
                # 随机选择和打乱题目
                if len(all_questions) > 10:
                    # 如果题目数大于10，随机选择10道题
                    selected_questions = random.sample(all_questions, 10)
                    print(f"[OK] 领域题目数({len(all_questions)}) > 10，随机选择10道题")
                else:
                    # 如果题目数小于等于10，返回所有题目
                    selected_questions = all_questions
                    print(f"[OK] 领域题目数({len(all_questions)}) <= 10，返回全部题目")
                
                # 打乱题目顺序
                random.shuffle(selected_questions)
                
                # 转换数据格式以匹配前端需求
                formatted_questions = []
                for q in selected_questions:
                    question_type = q.get('question_type', 'multiple_choice')
                    
                    if question_type == 'fill_in_blank':
                        # 填空题格式
                        formatted_questions.append({
                            'id': q['id'],
                            'title': q['title'],
                            'question_type': 'fill_in_blank',
                            'question_image': q.get('question_image'),
                            'fill_in_answer': q.get('fill_in_answer', ''),
                            'fill_in_keywords': q.get('fill_in_keywords', ''),
                            'correct': q.get('correct_answer', ''),
                            'category': q['category_name'],
                            'explanation': q.get('explanation', ''),
                            'explanation_image': q.get('explanation_image'),
                            'difficulty': q.get('difficulty', 'medium')
                        })
                    else:
                        # 选择题格式
                        correct_answer = q['correct_answer']
                        correct_index = {'A': 0, 'B': 1, 'C': 2, 'D': 3}.get(correct_answer, 0)
                        
                        formatted_questions.append({
                            'id': q['id'],
                            'title': q['title'],
                            'question_type': 'multiple_choice',
                            'question_image': q.get('question_image'),
                            'options': [q['option_a'], q['option_b'], q['option_c'], q['option_d']],
                            'option_a_image': q.get('option_a_image'),
                            'option_b_image': q.get('option_b_image'),
                            'option_c_image': q.get('option_c_image'),
                            'option_d_image': q.get('option_d_image'),
                            'correct': correct_index,
                            'category': q['category_name'],
                            'explanation': q.get('explanation', ''),
                            'explanation_image': q.get('explanation_image'),
                            'difficulty': q.get('difficulty', 'medium')
                        })
                
                print(f"[OK] 最终返回 {len(formatted_questions)} 道题目")

            conn.close()
            return jsonify({'success': True, 'questions': formatted_questions})
            
        except Exception as e:
            print(f"数据库错误: {e}")
            import traceback
            traceback.print_exc()
            return jsonify({'success': False, 'error': f'数据库查询失败: {str(e)}'})
    
    # 如果没有启用数据库，返回错误
    return jsonify({'success': False, 'error': '未启用数据库，请配置数据库'})


@app.route("/api/login", methods=['POST'])
def login_api():
    """用户登录API"""
    try:
        print("收到登录请求")
        
        if not request.is_json:
            print("错误: 请求不是JSON格式")
            return jsonify({'success': False, 'message': '请求格式错误'}), 400
        
        data = request.get_json()
        
        if not data:
            print("错误: 未收到JSON数据")
            return jsonify({'success': False, 'message': '未收到数据'}), 400
        
        username = data.get('username', '').strip()
        password = data.get('password', '')
        
        print(f"登录信息 - 用户名: {username}")
        
        if not username or not password:
            return jsonify({'success': False, 'message': '请输入用户名和密码'})
        
        # 从数据库获取用户
        user = get_user_from_db(username)
        
        if not user:
            print(f"[ERROR] 登录失败: 用户 '{username}' 不存在")
            return jsonify({'success': False, 'message': '用户名或密码错误'})
        
        # 验证密码
        if not verify_password(password, user['password']):
            print(f"[ERROR] 登录失败: 用户 '{username}' 密码错误")
            return jsonify({'success': False, 'message': '用户名或密码错误'})
        
        # 登录成功，设置session
        session['user_id'] = user['id']
        session['username'] = username
        session['logged_in'] = True
        
        print(f"[OK] 登录成功: 用户 '{username}'")
        return jsonify({'success': True, 'message': '登录成功'})
        
    except Exception as e:
        print(f"登录API错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'服务器错误: {str(e)}'}), 500


@app.route("/api/register", methods=['POST'])
def register_api():
    """用户注册API"""
    try:
        print("收到注册请求")
        
        # 检查Content-Type
        if not request.is_json:
            print("错误: 请求不是JSON格式")
            return jsonify({'success': False, 'message': '请求格式错误'}), 400
        
        data = request.get_json()
        
        if not data:
            print("错误: 未收到JSON数据")
            return jsonify({'success': False, 'message': '未收到数据'}), 400
        
        username = data.get('username', '').strip()
        email = data.get('email', '').strip()
        password = data.get('password', '')
        
        print(f"注册信息 - 用户名: {username}, 邮箱: {email}")
        
        # 验证输入
        if not username or not email or not password:
            return jsonify({'success': False, 'message': '请填写所有必填项'})
        
        if len(username) < 3 or len(username) > 20:
            return jsonify({'success': False, 'message': '用户名长度应为3-20个字符'})
        
        if len(password) < 6:
            return jsonify({'success': False, 'message': '密码长度至少为6位'})
        
        # 简单的邮箱验证
        if '@' not in email or '.' not in email:
            return jsonify({'success': False, 'message': '请输入有效的邮箱地址'})
        
        # 检查用户名是否已存在
        existing_user = get_user_from_db(username)
        if existing_user:
            return jsonify({'success': False, 'message': '用户名已存在'})
        
        # 检查邮箱是否已被注册
        conn = get_db_connection()
        if conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT id FROM users WHERE email = %s", [email])
                if cursor.fetchone():
                    conn.close()
                    return jsonify({'success': False, 'message': '邮箱已被注册'})
            conn.close()
        
        # 创建新用户
        if not create_user_in_db(username, email, password):
            return jsonify({'success': False, 'message': '注册失败，请稍后重试'})
        
        print(f"[OK] 注册成功: 用户 '{username}' ({email})")
        
        # 从数据库获取用户ID
        user = get_user_from_db(username)
        
        # 自动登录
        session['user_id'] = user['id']
        session['username'] = username
        session['logged_in'] = True
        
        return jsonify({'success': True, 'message': '注册成功'})
        
    except Exception as e:
        print(f"注册API错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'服务器错误: {str(e)}'}), 500


@app.route("/api/logout", methods=['POST'])
def logout_api():
    """用户登出API"""
    username = session.get('username', '未知')
    session.clear()
    print(f"[OK] 登出成功: 用户 '{username}'")
    return jsonify({'success': True, 'message': '登出成功'})


@app.route("/api/check-auth", methods=['GET'])
def check_auth():
    """检查用户登录状态"""
    if session.get('logged_in'):
        return jsonify({
            'success': True, 
            'logged_in': True, 
            'username': session.get('username')
        })
    return jsonify({'success': True, 'logged_in': False})


@app.route("/api/admin/login", methods=['POST'])
def admin_login_api():
    """管理员登录API"""
    try:
        print("收到管理员登录请求")
        data = request.get_json()
        
        if not data:
            print("错误: 未收到JSON数据")
            return jsonify({'success': False, 'message': '无效的请求数据'}), 400
        
        password = data.get('password', '')
        print(f"接收到的密码: {password[:3]}...")
        print(f"期望的密码: {ADMIN_PASSWORD[:3]}...")
        
        if not password:
            return jsonify({'success': False, 'message': '请输入密码'})
        
        if password == ADMIN_PASSWORD:
            session['admin_logged_in'] = True
            session['admin_login_time'] = get_beijing_time().strftime('%Y-%m-%d %H:%M:%S')
            print(f"[OK] 管理员登录成功")
            return jsonify({'success': True, 'message': '登录成功'})
        else:
            print(f"[ERROR] 管理员登录失败: 密码错误")
            return jsonify({'success': False, 'message': '密码错误'})
    except Exception as e:
        print(f"登录API错误: {str(e)}")
        return jsonify({'success': False, 'message': f'服务器错误: {str(e)}'}), 500


@app.route("/api/admin/logout", methods=['POST'])
def admin_logout_api():
    """管理员登出API"""
    session.pop('admin_logged_in', None)
    session.pop('admin_login_time', None)
    print("[OK] 管理员登出")
    return jsonify({'success': True, 'message': '登出成功'})


@app.route("/api/admin/dashboard", methods=['GET'])
def admin_dashboard():
    """管理员仪表盘数据"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 统计总用户数
            cursor.execute("SELECT COUNT(*) as count FROM users")
            total_users = cursor.fetchone()['count']
            
            # 统计答题总数（从quiz_results表）
            cursor.execute("SELECT COUNT(*) as count FROM quiz_results")
            total_quiz_count = cursor.fetchone()['count']
            
            # 统计总得分（从quiz_results表）
            cursor.execute("SELECT SUM(score) as total FROM quiz_results")
            result = cursor.fetchone()
            total_score = result['total'] if result['total'] else 0
            
            # 计算平均得分
            avg_score = total_score / total_quiz_count if total_quiz_count > 0 else 0
            
            # 查询最近注册的用户
            cursor.execute("""
                SELECT username, created_at 
                FROM users 
                ORDER BY created_at DESC 
                LIMIT 5
            """)
            recent_activities = [
                {
                    'icon': 'user',
                    'title': f"新用户注册: {row['username']}",
                    'time': row['created_at'].strftime('%Y-%m-%d %H:%M:%S') if isinstance(row['created_at'], datetime) else str(row['created_at'])
                }
                for row in cursor.fetchall()
            ]
            
            # 添加最近的答题记录
            cursor.execute("""
                SELECT u.username, r.score, r.created_at
                FROM quiz_results r
                LEFT JOIN users u ON r.user_id = u.id
                ORDER BY r.created_at DESC
                LIMIT 5
            """)
            quiz_activities = [
                {
                    'icon': 'quiz',
                    'title': f"答题完成: {row['username'] or '匿名用户'}得分 {row['score']}",
                    'time': row['created_at'].strftime('%Y-%m-%d %H:%M:%S') if isinstance(row['created_at'], datetime) else str(row['created_at'])
                }
                for row in cursor.fetchall()
            ]
            
            # 合并活动
            recent_activities.extend(quiz_activities)
            recent_activities.sort(key=lambda x: x['time'], reverse=True)
            recent_activities = recent_activities[:10]
        
        conn.close()
        
        return jsonify({
            'success': True,
            'total_users': total_users,
            'total_quiz_count': total_quiz_count,
            'total_score': total_score,
            'avg_score': round(avg_score, 1),
            'recent_activities': recent_activities
        })
    except Exception as e:
        print(f"[ERROR] 获取仪表盘数据失败: {e}")
        return jsonify({'success': False, 'message': f'获取数据失败: {str(e)}'})


@app.route("/api/admin/users", methods=['GET'])
def admin_users():
    """管理员获取用户列表"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT id, username, email, score, quiz_count, created_at, updated_at
                FROM users
                ORDER BY created_at DESC
            """)
            users_list = [
                {
                    **row,
                    'created_at': row['created_at'].strftime('%Y-%m-%d %H:%M:%S') if isinstance(row['created_at'], datetime) else str(row['created_at']),
                    'updated_at': row['updated_at'].strftime('%Y-%m-%d %H:%M:%S') if isinstance(row['updated_at'], datetime) else str(row['updated_at'])
                }
                for row in cursor.fetchall()
            ]
        
        conn.close()
        
        return jsonify({
            'success': True,
            'users': users_list
        })
    except Exception as e:
        print(f"[ERROR] 获取用户列表失败: {e}")
        return jsonify({'success': False, 'message': f'获取用户列表失败: {str(e)}'})


@app.route("/api/admin/statistics", methods=['GET'])
def admin_statistics():
    """管理员统计数据"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        today = get_beijing_time().strftime('%Y-%m-%d')
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 今日新用户
            cursor.execute("SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = %s", [today])
            today_users = cursor.fetchone()['count']
            
            # 今日活跃用户（有答题记录的用户）
            cursor.execute("""
                SELECT COUNT(DISTINCT user_id) as count 
                FROM quiz_results 
                WHERE DATE(created_at) = %s AND user_id IS NOT NULL
            """, [today])
            active_users = cursor.fetchone()['count']
            
            # 今日答题次数（从答题记录表）
            cursor.execute("""
                SELECT COUNT(*) as count 
                FROM quiz_results 
                WHERE DATE(created_at) = %s
            """, [today])
            today_quiz = cursor.fetchone()['count']
            
            # 平均答题次数（从答题记录表统计）
            cursor.execute("""
                SELECT AVG(cnt) as avg 
                FROM (
                    SELECT COUNT(*) as cnt 
                    FROM quiz_results 
                    WHERE user_id IS NOT NULL
                    GROUP BY user_id
                ) as user_quiz
            """)
            result = cursor.fetchone()
            avg_quiz = round(float(result['avg'] or 0), 1)
            
            # 最高/最低得分（从答题记录表，单次答题得分）
            cursor.execute("""
                SELECT MAX(score) as max_score, MIN(score) as min_score 
                FROM quiz_results
            """)
            result = cursor.fetchone()
            max_score = result['max_score'] or 0
            min_score = result['min_score'] or 0
            
            # 平均得分
            cursor.execute("SELECT AVG(score) as avg FROM quiz_results")
            result = cursor.fetchone()
            avg_score = round(float(result['avg'] or 0), 1)
        
        conn.close()
        
        return jsonify({
            'success': True,
            'today_users': today_users,
            'active_users': active_users,
            'today_quiz': today_quiz,
            'avg_quiz': avg_quiz,
            'max_score': max_score,
            'min_score': min_score,
            'avg_score': avg_score
        })
    except Exception as e:
        print(f"[ERROR] 获取统计数据失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取统计数据失败: {str(e)}'})


@app.route("/api/save-quiz-result", methods=['POST'])
def save_quiz_result():
    """保存答题结果API"""
    data = request.get_json()
    
    # 如果用户已登录，更新用户数据
    if session.get('logged_in') and USE_DATABASE:
        username = session.get('username')
        print(f"[INFO] 准备更新用户 '{username}' 的答题记录")
        try:
            user = get_user_from_db(username)
            if user:
                current_quiz_count = user.get('quiz_count', 0) or 0
                current_score = user.get('score', 0) or 0
                new_quiz_count = current_quiz_count + 1
                new_score = current_score + data.get('score', 0)
                
                print(f"[INFO] 当前数据: quiz_count={current_quiz_count}, score={current_score}")
                print(f"[INFO] 新数据: quiz_count={new_quiz_count}, score={new_score}")
                
                if update_user_in_db(username, quiz_count=new_quiz_count, score=new_score):
                    print(f"[OK] 已更新用户 '{username}' 的答题记录")
                else:
                    print(f"[ERROR] 更新用户数据失败")
            else:
                print(f"[ERROR] 未找到用户 '{username}'")
        except Exception as e:
            print(f"[ERROR] 更新用户数据失败: {e}")
            import traceback
            traceback.print_exc()
    
    if USE_DATABASE:
        # 使用数据库保存结果
        try:
            conn = get_db_connection()
            if not conn:
                return jsonify({'success': False, 'error': '数据库连接失败，无法保存结果'})

            with conn.cursor() as cursor:
                # 获取分类ID
                cursor.execute("SELECT id FROM categories WHERE name = %s", [data.get('category', '')])
                category_result = cursor.fetchone()
                
                if category_result:
                    category_id = category_result[0]
                else:
                    # 如果分类不存在，创建一个
                    cursor.execute("INSERT INTO categories (name, description) VALUES (%s, %s)", 
                                 [data.get('category', '未分类'), '用户生成的分类'])
                    category_id = cursor.lastrowid
                    conn.commit()
                
                # 插入答题结果
                cursor.execute("""
                    INSERT INTO quiz_results 
                    (category_id, category_name, correct_count, wrong_count, score, time_elapsed, user_id)
                    VALUES (%s, %s, %s, %s, %s, %s, %s)
                """, [
                    category_id,
                    data.get('category', '未分类'),
                    data.get('correctCount', 0),
                    data.get('wrongCount', 0),
                    data.get('score', 0),
                    data.get('timeElapsed', 0),
                    session.get('user_id') if session.get('logged_in') else None
                ])
                
                quiz_result_id = cursor.lastrowid
                
                # 保存每道题的详细答题记录
                questions_data = data.get('questions', [])
                user_answers = data.get('userAnswers', [])
                fill_in_answers = data.get('fillInAnswers', [])
                
                if questions_data and len(questions_data) > 0:
                    print(f"[INFO] 保存 {len(questions_data)} 道题的详细记录")
                    for i, question in enumerate(questions_data):
                        question_type = question.get('question_type', 'multiple_choice')
                        
                        if question_type == 'fill_in_blank':
                            # 填空题处理
                            user_fill_answer = fill_in_answers[i] if i < len(fill_in_answers) else ''
                            correct_fill_answer = question.get('fill_in_answer', '')
                            
                            # 检查填空题答案是否正确
                            is_correct = check_fill_in_answer(user_fill_answer, correct_fill_answer, question.get('fill_in_keywords', ''))
                            
                            cursor.execute("""
                                INSERT INTO quiz_answers 
                                (quiz_result_id, question_id, question_title, question_type,
                                 fill_in_user_answer, fill_in_correct_answer, 
                                 is_correct, explanation)
                                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                            """, [
                                quiz_result_id,
                                question.get('id', 0),
                                question.get('title', ''),
                                'fill_in_blank',
                                user_fill_answer,
                                correct_fill_answer,
                                is_correct,
                                question.get('explanation', '')
                            ])
                        else:
                            # 选择题处理
                            user_answer_index = user_answers[i] if i < len(user_answers) else None
                            correct_index = question.get('correct')
                            
                            # 将索引转换为A/B/C/D
                            answer_map = {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
                            user_answer = answer_map.get(user_answer_index) if user_answer_index is not None else None
                            correct_answer = answer_map.get(correct_index) if correct_index is not None else None
                            
                            is_correct = (user_answer == correct_answer) if user_answer and correct_answer else False
                            
                            cursor.execute("""
                                INSERT INTO quiz_answers 
                                (quiz_result_id, question_id, question_title, question_type,
                                 option_a, option_b, option_c, option_d, 
                                 correct_answer, user_answer, is_correct, explanation)
                                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                            """, [
                                quiz_result_id,
                                question.get('id', 0),
                                question.get('title', ''),
                                'multiple_choice',
                                question.get('options', ['', '', '', ''])[0] if len(question.get('options', [])) > 0 else '',
                                question.get('options', ['', '', '', ''])[1] if len(question.get('options', [])) > 1 else '',
                                question.get('options', ['', '', '', ''])[2] if len(question.get('options', [])) > 2 else '',
                                question.get('options', ['', '', '', ''])[3] if len(question.get('options', [])) > 3 else '',
                                correct_answer,
                                user_answer,
                                is_correct,
                                question.get('explanation', '')
                            ])

            conn.commit()
            conn.close()
            
            print(f"[OK] 答题结果已保存到数据库")
            return jsonify({'success': True, 'message': '答题结果已保存到数据库'})
            
        except Exception as e:
            print(f"[ERROR] 保存结果到数据库失败: {e}")
            import traceback
            traceback.print_exc()
            return jsonify({'success': False, 'error': f'保存失败: {str(e)}'})
    
    # 如果没有启用数据库
    return jsonify({'success': False, 'error': '未启用数据库，无法保存答题结果'})


@app.route("/api/user/info", methods=['GET'])
def user_info():
    """获取用户基本信息 - 移动端使用"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        username = session.get('username')
        user = get_user_from_db(username)
        
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'})
        
        return jsonify({
            'success': True,
            'user': {
                'id': user['id'],
                'username': user['username'],
                'email': user['email'],
                'avatar': user.get('avatar') or None,
                'created_at': user['created_at'].strftime('%Y-%m-%d %H:%M:%S') if hasattr(user.get('created_at'), 'strftime') else str(user.get('created_at', ''))
            }
        })
    except Exception as e:
        print(f"[ERROR] 获取用户信息失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取用户信息失败: {str(e)}'})


@app.route("/api/user/stats", methods=['GET'])
def user_stats():
    """获取用户统计数据 - 移动端使用"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '用户ID不存在'})
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取统计数据
            cursor.execute("""
                SELECT 
                    COUNT(*) as total_quizzes,
                    COALESCE(ROUND(AVG(score), 1), 0) as average_score,
                    COALESCE(SUM(score), 0) as total_score,
                    COALESCE(ROUND(SUM(correct_count) * 100.0 / NULLIF(SUM(correct_count + wrong_count), 0), 1), 0) as accuracy
                FROM quiz_results
                WHERE user_id = %s
            """, [user_id])
            
            stats = cursor.fetchone()
            
        conn.close()
        
        return jsonify({
            'success': True,
            'stats': {
                'total_quizzes': int(stats['total_quizzes'] or 0),
                'average_score': float(stats['average_score'] or 0),
                'total_score': int(stats['total_score'] or 0),
                'accuracy': float(stats['accuracy'] or 0)
            }
        })
    except Exception as e:
        print(f"[ERROR] 获取用户统计失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取统计失败: {str(e)}'})


@app.route("/api/user/profile", methods=['GET'])
def user_profile():
    """获取用户资料 - PC端使用"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        username = session.get('username')
        user = get_user_from_db(username)
        
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'})
        
        # 移除密码信息
        user.pop('password', None)
        
        return jsonify({
            'success': True,
            'user': user
        })
    except Exception as e:
        print(f"[ERROR] 获取用户资料失败: {e}")
        return jsonify({'success': False, 'message': f'获取用户资料失败: {str(e)}'})


@app.route("/api/user/quiz-history", methods=['GET'])
def user_quiz_history():
    """获取用户答题记录"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        user_id = session.get('user_id')
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT id, category_name, correct_count, wrong_count, score, time_elapsed, created_at
                FROM quiz_results
                WHERE user_id = %s
                ORDER BY created_at DESC
                LIMIT 50
            """, [user_id])
            
            history = []
            for row in cursor.fetchall():
                history.append({
                    'id': row['id'],
                    'category_name': row['category_name'],
                    'correct_count': row['correct_count'],
                    'wrong_count': row['wrong_count'],
                    'score': row['score'],
                    'time_elapsed': row['time_elapsed'],
                    'created_at': row['created_at'].strftime('%Y-%m-%d %H:%M:%S') if isinstance(row['created_at'], datetime) else str(row['created_at'])
                })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'history': history
        })
    except Exception as e:
        print(f"[ERROR] 获取答题记录失败: {e}")
        return jsonify({'success': False, 'message': f'获取答题记录失败: {str(e)}'})


@app.route("/api/quiz/detail/<int:quiz_id>", methods=['GET'])
def get_quiz_detail(quiz_id):
    """获取答题详细记录"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        user_id = session.get('user_id')
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 验证这是否是用户自己的答题记录
            cursor.execute("""
                SELECT * FROM quiz_results
                WHERE id = %s AND user_id = %s
            """, [quiz_id, user_id])
            
            quiz_result = cursor.fetchone()
            if not quiz_result:
                conn.close()
                return jsonify({'success': False, 'message': '未找到答题记录或无权访问'})
            
            # 获取详细答题记录
            cursor.execute("""
                SELECT * FROM quiz_answers
                WHERE quiz_result_id = %s
                ORDER BY id
            """, [quiz_id])
            
            answers = []
            for row in cursor.fetchall():
                answers.append({
                    'question_title': row['question_title'],
                    'option_a': row['option_a'],
                    'option_b': row['option_b'],
                    'option_c': row['option_c'],
                    'option_d': row['option_d'],
                    'correct_answer': row['correct_answer'],
                    'user_answer': row['user_answer'],
                    'is_correct': bool(row['is_correct']),
                    'explanation': row.get('explanation', '')
                })
        
        conn.close()
        
        return jsonify({
            'success': True,
            'quiz_result': {
                'id': quiz_result['id'],
                'category_name': quiz_result['category_name'],
                'correct_count': quiz_result['correct_count'],
                'wrong_count': quiz_result['wrong_count'],
                'score': quiz_result['score'],
                'time_elapsed': quiz_result['time_elapsed'],
                'created_at': quiz_result['created_at'].strftime('%Y-%m-%d %H:%M:%S') if isinstance(quiz_result['created_at'], datetime) else str(quiz_result['created_at'])
            },
            'answers': answers
        })
    except Exception as e:
        print(f"[ERROR] 获取答题详情失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取答题详情失败: {str(e)}'})


@app.route("/api/user/update", methods=['POST'])
@app.route("/api/user/update-info", methods=['POST'])
def user_update_info():
    """更新用户信息"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        data = request.get_json()
        username = session.get('username')
        new_username = data.get('username', '').strip()
        new_email = data.get('email', '').strip()
        
        # 验证
        if not new_username or not new_email:
            return jsonify({'success': False, 'message': '请填写所有字段'})
        
        if len(new_username) < 3 or len(new_username) > 20:
            return jsonify({'success': False, 'message': '用户名长度应为3-20个字符'})
        
        if '@' not in new_email or '.' not in new_email:
            return jsonify({'success': False, 'message': '请输入有效的邮箱地址'})
        
        # 检查新用户名是否已被使用（如果不是当前用户名）
        if new_username != username:
            existing_user = get_user_from_db(new_username)
            if existing_user:
                return jsonify({'success': False, 'message': '用户名已被使用'})
        
        # 更新用户信息
        update_data = {'email': new_email}
        if new_username != username:
            update_data['username'] = new_username
        
        if update_user_in_db(username, **update_data):
            # 更新session
            if new_username != username:
                session['username'] = new_username
            
            print(f"[OK] 用户 '{username}' 更新信息成功")
            return jsonify({'success': True, 'message': '信息更新成功'})
        else:
            return jsonify({'success': False, 'message': '更新失败'})
            
    except Exception as e:
        print(f"[ERROR] 更新用户信息失败: {e}")
        return jsonify({'success': False, 'message': f'更新失败: {str(e)}'})


@app.route("/api/user/update-password", methods=['POST'])
def user_update_password():
    """修改用户密码"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        data = request.get_json()
        username = session.get('username')
        old_password = data.get('old_password', '')
        new_password = data.get('new_password', '')
        
        # 验证
        if not old_password or not new_password:
            return jsonify({'success': False, 'message': '请填写所有字段'})
        
        if len(new_password) < 6:
            return jsonify({'success': False, 'message': '新密码长度至少为6位'})
        
        # 获取用户
        user = get_user_from_db(username)
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'})
        
        # 验证旧密码
        if not verify_password(old_password, user['password']):
            return jsonify({'success': False, 'message': '当前密码错误'})
        
        # 更新密码
        new_password_hash = hash_password(new_password)
        if update_user_in_db(username, password=new_password_hash):
            print(f"[OK] 用户 '{username}' 修改密码成功")
            return jsonify({'success': True, 'message': '密码修改成功'})
        else:
            return jsonify({'success': False, 'message': '修改失败'})
            
    except Exception as e:
        print(f"[ERROR] 修改密码失败: {e}")
        return jsonify({'success': False, 'message': f'修改失败: {str(e)}'})


@app.route("/api/user/upload-avatar", methods=['POST'])
def upload_avatar():
    """上传用户头像"""
    print(f"[DEBUG] 头像上传API被调用")
    if not session.get('logged_in'):
        print(f"[ERROR] 用户未登录")
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        # 检查是否有文件
        if 'avatar' not in request.files:
            print(f"[ERROR] 请求中没有avatar文件")
            return jsonify({'success': False, 'message': '没有选择文件'})
        
        file = request.files['avatar']
        print(f"[DEBUG] 接收到文件: {file.filename}, 大小: {len(file.read())} bytes")
        file.seek(0)  # 重置文件指针
        
        # 检查文件名
        if file.filename == '':
            print(f"[ERROR] 文件名为空")
            return jsonify({'success': False, 'message': '文件名为空'})
        
        # 检查文件类型
        if not allowed_file(file.filename):
            print(f"[ERROR] 不支持的文件类型: {file.filename}")
            return jsonify({'success': False, 'message': '不支持的文件类型，请上传图片文件（png, jpg, jpeg, gif, webp）'})
        
        # 生成唯一文件名
        file_ext = file.filename.rsplit('.', 1)[1].lower()
        unique_filename = f"{uuid.uuid4().hex}.{file_ext}"
        
        # 保存文件
        file_path = os.path.join(AVATAR_UPLOAD_FOLDER, unique_filename)
        print(f"[DEBUG] 保存文件到: {file_path}")
        file.save(file_path)
        print(f"[DEBUG] 文件保存成功")
        
        # 构建访问URL
        avatar_url = f'/static/uploads/avatars/{unique_filename}'
        print(f"[DEBUG] 头像URL: {avatar_url}")
        
        # 更新数据库中的用户头像
        username = session.get('username')
        print(f"[DEBUG] 当前用户: {username}")
        
        if not USE_DATABASE:
            print(f"[DEBUG] 数据库未启用，直接返回成功")
            return jsonify({
                'success': True,
                'message': '头像上传成功',
                'avatar_url': avatar_url
            })
        
        conn = get_db_connection()
        if not conn:
            print(f"[ERROR] 数据库连接失败")
            # 删除已上传的文件
            if os.path.exists(file_path):
                os.remove(file_path)
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor() as cursor:
            # 获取旧头像路径
            print(f"[DEBUG] 查询用户旧头像")
            cursor.execute("SELECT avatar FROM users WHERE username = %s", [username])
            result = cursor.fetchone()
            old_avatar = result[0] if result and result[0] else None
            print(f"[DEBUG] 旧头像: {old_avatar}")
            
            # 更新新头像
            updated_at = get_beijing_time().strftime('%Y-%m-%d %H:%M:%S')
            print(f"[DEBUG] 更新用户头像到数据库")
            cursor.execute("""
                UPDATE users 
                SET avatar = %s, updated_at = %s
                WHERE username = %s
            """, [avatar_url, updated_at, username])
            
            affected_rows = cursor.rowcount
            print(f"[DEBUG] 影响的行数: {affected_rows}")
            
            conn.commit()
            print(f"[DEBUG] 数据库更新已提交")
            
            # 删除旧头像文件（如果存在且不是默认头像）
            if old_avatar and old_avatar.startswith('/static/uploads/avatars/'):
                old_avatar_path = old_avatar.replace('/static/', 'static/')
                if os.path.exists(old_avatar_path):
                    try:
                        os.remove(old_avatar_path)
                    except:
                        pass
        
        conn.close()
        
        print(f"[OK] 用户 {username} 上传头像成功: {avatar_url}")
        return jsonify({
            'success': True,
            'message': '头像上传成功',
            'avatar_url': avatar_url
        })
        
    except Exception as e:
        print(f"[ERROR] 上传头像失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'上传失败: {str(e)}'})


@app.route("/api/user/achievements", methods=['GET'])
def get_user_achievements():
    """获取用户成就列表"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '用户ID不存在'})

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取所有成就
            cursor.execute("""
                SELECT a.*, ua.unlocked_at
                FROM achievements a
                LEFT JOIN user_achievements ua ON a.id = ua.achievement_id AND ua.user_id = %s
                WHERE a.status = 'active'
                ORDER BY a.rarity DESC, a.points DESC
            """, [user_id])

            achievements = cursor.fetchall()

            # 获取用户级别信息
            cursor.execute("""
                SELECT level, experience, total_experience
                FROM user_levels
                WHERE user_id = %s
            """, [user_id])

            level_info = cursor.fetchone()
            if not level_info:
                # 如果没有级别记录，创建默认记录
                cursor.execute("""
                    INSERT INTO user_levels (user_id, level, experience, total_experience)
                    VALUES (%s, 1, 0, 0)
                """, [user_id])
                conn.commit()
                level_info = {'level': 1, 'experience': 0, 'total_experience': 0}

        conn.close()

        # 处理成就数据
        unlocked_achievements = []
        locked_achievements = []

        for achievement in achievements:
            achievement_data = {
                'id': achievement['id'],
                'name': achievement['name'],
                'description': achievement['description'],
                'icon': achievement['icon'],
                'type': achievement['type'],
                'condition_value': achievement['condition_value'],
                'points': achievement['points'],
                'rarity': achievement['rarity']
            }

            if achievement['unlocked_at']:
                achievement_data['unlocked_at'] = achievement['unlocked_at'].strftime('%Y-%m-%d %H:%M:%S')
                unlocked_achievements.append(achievement_data)
            else:
                locked_achievements.append(achievement_data)

        return jsonify({
            'success': True,
            'achievements': {
                'unlocked': unlocked_achievements,
                'locked': locked_achievements
            },
            'level': level_info
        })

    except Exception as e:
        print(f"[ERROR] 获取用户成就失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取成就失败: {str(e)}'})


@app.route("/api/user/check-achievements", methods=['POST'])
def check_user_achievements():
    """检查并解锁用户成就"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '用户ID不存在'})

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取用户统计数据
            cursor.execute("""
                SELECT COUNT(*) as quiz_count,
                       AVG((correct_count / (correct_count + wrong_count)) * 100) as avg_accuracy,
                       MAX(score) as max_score,
                       MIN(time_elapsed) as min_time
                FROM quiz_results
                WHERE user_id = %s
            """, [user_id])

            stats = cursor.fetchone()

            # 获取用户已解锁的成就
            cursor.execute("""
                SELECT achievement_id FROM user_achievements WHERE user_id = %s
            """, [user_id])

            unlocked_ids = [row['achievement_id'] for row in cursor.fetchall()]

            # 检查可以解锁的成就
            cursor.execute("""
                SELECT * FROM achievements
                WHERE status = 'active' AND id NOT IN %s
            """, [tuple(unlocked_ids) if unlocked_ids else (0,)])

            achievements = cursor.fetchall()

            new_unlocks = []

            for achievement in achievements:
                should_unlock = False

                if achievement['type'] == 'quiz_count' and stats['quiz_count'] >= achievement['condition_value']:
                    should_unlock = True
                elif achievement['type'] == 'accuracy' and stats['avg_accuracy'] >= achievement['condition_value']:
                    should_unlock = True
                elif achievement['type'] == 'score' and stats['max_score'] >= achievement['condition_value']:
                    should_unlock = True
                elif achievement['type'] == 'speed' and stats['min_time'] <= achievement['condition_value']:
                    should_unlock = True
                elif achievement['type'] == 'category_master':
                    # 检查是否掌握所有科目
                    cursor.execute("""
                        SELECT COUNT(DISTINCT category_id) as category_count
                        FROM quiz_results
                        WHERE user_id = %s
                    """, [user_id])
                    category_count = cursor.fetchone()['category_count']
                    if category_count >= achievement['condition_value']:
                        should_unlock = True

                if should_unlock:
                    # 解锁成就
                    cursor.execute("""
                        INSERT INTO user_achievements (user_id, achievement_id)
                        VALUES (%s, %s)
                    """, [user_id, achievement['id']])

                    # 增加经验值
                    cursor.execute("""
                        INSERT INTO user_levels (user_id, level, experience, total_experience)
                        VALUES (%s, 1, %s, %s)
                        ON DUPLICATE KEY UPDATE
                        experience = experience + %s,
                        total_experience = total_experience + %s,
                        level = FLOOR((experience + %s) / 100) + 1
                    """, [user_id, achievement['points'], achievement['points'],
                         achievement['points'], achievement['points'], achievement['points']])

                    new_unlocks.append({
                        'id': achievement['id'],
                        'name': achievement['name'],
                        'icon': achievement['icon'],
                        'rarity': achievement['rarity'],
                        'points': achievement['points']
                    })

            if new_unlocks:
                conn.commit()

        conn.close()

        return jsonify({
            'success': True,
            'new_unlocks': new_unlocks
        })

    except Exception as e:
        print(f"[ERROR] 检查成就失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'检查成就失败: {str(e)}'})


@app.route("/api/user/favorites", methods=['GET'])
def get_user_favorites():
    """获取用户收藏夹"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '用户ID不存在'})

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取收藏的题目
            cursor.execute("""
                SELECT f.*, q.title, q.category_id, c.name as category_name
                FROM favorites f
                JOIN questions q ON f.item_id = q.id AND f.item_type = 'question'
                JOIN categories c ON q.category_id = c.id
                WHERE f.user_id = %s
                ORDER BY f.created_at DESC
            """, [user_id])

            favorite_questions = cursor.fetchall()

            # 获取收藏的分类
            cursor.execute("""
                SELECT f.*, c.name, c.description, c.icon, c.question_count
                FROM favorites f
                JOIN categories c ON f.item_id = c.id AND f.item_type = 'category'
                WHERE f.user_id = %s
                ORDER BY f.created_at DESC
            """, [user_id])

            favorite_categories = cursor.fetchall()

        conn.close()

        return jsonify({
            'success': True,
            'favorites': {
                'questions': favorite_questions,
                'categories': favorite_categories
            }
        })

    except Exception as e:
        print(f"[ERROR] 获取收藏夹失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取收藏夹失败: {str(e)}'})


@app.route("/api/user/favorites/<item_type>/<int:item_id>", methods=['POST'])
def toggle_favorite(item_type, item_id):
    """切换收藏状态"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    if item_type not in ['question', 'category']:
        return jsonify({'success': False, 'message': '无效的收藏类型'})

    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '用户ID不存在'})

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor() as cursor:
            # 检查是否已收藏
            cursor.execute("""
                SELECT id FROM favorites
                WHERE user_id = %s AND item_type = %s AND item_id = %s
            """, [user_id, item_type, item_id])

            existing = cursor.fetchone()

            if existing:
                # 取消收藏
                cursor.execute("""
                    DELETE FROM favorites
                    WHERE user_id = %s AND item_type = %s AND item_id = %s
                """, [user_id, item_type, item_id])
                action = 'removed'
            else:
                # 添加收藏
                cursor.execute("""
                    INSERT INTO favorites (user_id, item_type, item_id)
                    VALUES (%s, %s, %s)
                """, [user_id, item_type, item_id])
                action = 'added'

            conn.commit()

        conn.close()

        return jsonify({
            'success': True,
            'action': action,
            'item_type': item_type,
            'item_id': item_id
        })

    except Exception as e:
        print(f"[ERROR] 切换收藏状态失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'操作失败: {str(e)}'})


@app.route("/api/user/learning-goals", methods=['GET'])
def get_learning_goals():
    """获取学习目标"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '用户ID不存在'})

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT * FROM learning_goals
                WHERE user_id = %s AND end_date >= CURDATE()
                ORDER BY goal_type, start_date DESC
            """, [user_id])

            goals = cursor.fetchall()

        conn.close()

        # 计算完成进度
        for goal in goals:
            if goal['goal_type'] == 'daily':
                # 每日目标：检查今天的数据
                start_date = datetime.now().date()
                end_date = start_date
            elif goal['goal_type'] == 'weekly':
                # 每周目标：检查本周的数据
                today = datetime.now().date()
                start_date = today - timedelta(days=today.weekday())
                end_date = start_date + timedelta(days=6)
            else:  # monthly
                # 每月目标：检查本月的数据
                today = datetime.now().date()
                start_date = today.replace(day=1)
                end_date = (start_date + timedelta(days=32)).replace(day=1) - timedelta(days=1)

            goal['start_date'] = start_date.strftime('%Y-%m-%d')
            goal['end_date'] = end_date.strftime('%Y-%m-%d')

            # 这里可以添加实际进度的计算逻辑

        return jsonify({
            'success': True,
            'goals': goals
        })

    except Exception as e:
        print(f"[ERROR] 获取学习目标失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取学习目标失败: {str(e)}'})


@app.route("/api/user/learning-goals", methods=['POST'])
def set_learning_goal():
    """设置学习目标"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        data = request.get_json()
        if not data:
            return jsonify({'success': False, 'message': '无效的请求数据'})

        user_id = session.get('user_id')
        goal_type = data.get('goal_type')
        target_quizzes = data.get('target_quizzes', 0)
        target_score = data.get('target_score', 0)
        target_accuracy = data.get('target_accuracy', 0)

        if goal_type not in ['daily', 'weekly', 'monthly']:
            return jsonify({'success': False, 'message': '无效的目标类型'})

        # 计算开始和结束日期
        today = datetime.now().date()
        if goal_type == 'daily':
            start_date = today
            end_date = today
        elif goal_type == 'weekly':
            start_date = today - timedelta(days=today.weekday())
            end_date = start_date + timedelta(days=6)
        else:  # monthly
            start_date = today.replace(day=1)
            end_date = (start_date + timedelta(days=32)).replace(day=1) - timedelta(days=1)

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor() as cursor:
            # 删除已存在的同类型目标
            cursor.execute("""
                DELETE FROM learning_goals
                WHERE user_id = %s AND goal_type = %s
            """, [user_id, goal_type])

            # 插入新目标
            cursor.execute("""
                INSERT INTO learning_goals (user_id, goal_type, target_quizzes, target_score, target_accuracy, start_date, end_date)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
            """, [user_id, goal_type, target_quizzes, target_score, target_accuracy, start_date, end_date])

            conn.commit()

        conn.close()

        return jsonify({
            'success': True,
            'message': '学习目标设置成功'
        })

    except Exception as e:
        print(f"[ERROR] 设置学习目标失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'设置失败: {str(e)}'})


@app.route("/api/user/preferences", methods=['GET'])
def get_user_preferences():
    """获取用户偏好设置"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '用户ID不存在'})

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT * FROM user_preferences WHERE user_id = %s
            """, [user_id])

            preferences = cursor.fetchone()

            if not preferences:
                # 创建默认偏好设置
                cursor.execute("""
                    INSERT INTO user_preferences (user_id) VALUES (%s)
                """, [user_id])
                conn.commit()

                preferences = {
                    'theme': 'light',
                    'notifications_enabled': True,
                    'reminder_enabled': False,
                    'reminder_time': '09:00:00',
                    'language': 'zh-CN'
                }
            else:
                # 转换数据库中的datetime.time对象为字符串
                if 'reminder_time' in preferences and hasattr(preferences['reminder_time'], 'strftime'):
                    preferences['reminder_time'] = preferences['reminder_time'].strftime('%H:%M:%S')

        conn.close()

        return jsonify({
            'success': True,
            'preferences': preferences
        })

    except Exception as e:
        print(f"[ERROR] 获取用户偏好失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取偏好失败: {str(e)}'})


@app.route("/api/user/preferences", methods=['POST'])
def update_user_preferences():
    """更新用户偏好设置"""
    if not session.get('logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        data = request.get_json()
        if not data:
            return jsonify({'success': False, 'message': '无效的请求数据'})

        user_id = session.get('user_id')
        theme = data.get('theme', 'light')
        notifications_enabled = data.get('notifications_enabled', True)
        reminder_enabled = data.get('reminder_enabled', False)
        reminder_time = data.get('reminder_time', '09:00:00')
        language = data.get('language', 'zh-CN')

        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})

        with conn.cursor() as cursor:
            cursor.execute("""
                INSERT INTO user_preferences (user_id, theme, notifications_enabled, reminder_enabled, reminder_time, language)
                VALUES (%s, %s, %s, %s, %s, %s)
                ON DUPLICATE KEY UPDATE
                theme = VALUES(theme),
                notifications_enabled = VALUES(notifications_enabled),
                reminder_enabled = VALUES(reminder_enabled),
                reminder_time = VALUES(reminder_time),
                language = VALUES(language)
            """, [user_id, theme, notifications_enabled, reminder_enabled, reminder_time, language])

            conn.commit()

        conn.close()

        return jsonify({
            'success': True,
            'message': '偏好设置更新成功'
        })

    except Exception as e:
        print(f"[ERROR] 更新用户偏好失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'更新失败: {str(e)}'})
   
                                                                                                                                                                    
@app.route("/api/leaderboard", methods=['GET'])
def leaderboard_api():
    """排行榜API - 支持PC端和移动端"""
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        # 兼容移动端(total/accuracy/count)和PC端(score/quiz/avg)参数
        rank_type = request.args.get('type', 'total')
        
        # 参数映射
        type_mapping = {
            'total': 'score',      # 移动端总分榜 -> 后端总分
            'accuracy': 'accuracy', # 移动端正确率榜
            'count': 'quiz',       # 移动端答题数榜 -> 后端答题次数
            'score': 'score',      # PC端兼容
            'quiz': 'quiz',        # PC端兼容
            'avg': 'avg'           # PC端兼容
        }
        
        rank_type = type_mapping.get(rank_type, 'score')
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 根据类型查询不同的排行榜
            if rank_type == 'score':
                # 总得分排行榜
                cursor.execute("""
                    SELECT u.id, u.username, u.email, u.avatar,
                           SUM(q.score) as total_score,
                           COUNT(q.id) as total_quizzes,
                           SUM(q.correct_count) as total_correct,
                           SUM(q.correct_count + q.wrong_count) as total_answered,
                           ROUND(SUM(q.score) * 1.0 / NULLIF(COUNT(q.id), 0), 1) as avg_score,
                           ROUND(SUM(q.correct_count) * 100.0 / NULLIF(SUM(q.correct_count + q.wrong_count), 0), 1) as accuracy
                    FROM users u
                    INNER JOIN quiz_results q ON u.id = q.user_id
                    GROUP BY u.id, u.username, u.email, u.avatar
                    HAVING total_quizzes > 0
                    ORDER BY total_score DESC
                    LIMIT 100
                """)
            elif rank_type == 'quiz':
                # 答题次数排行榜
                cursor.execute("""
                    SELECT u.id, u.username, u.email, u.avatar,
                           SUM(q.score) as total_score,
                           COUNT(q.id) as total_quizzes,
                           SUM(q.correct_count) as total_correct,
                           SUM(q.correct_count + q.wrong_count) as total_answered,
                           ROUND(SUM(q.score) * 1.0 / NULLIF(COUNT(q.id), 0), 1) as avg_score,
                           ROUND(SUM(q.correct_count) * 100.0 / NULLIF(SUM(q.correct_count + q.wrong_count), 0), 1) as accuracy
                    FROM users u
                    INNER JOIN quiz_results q ON u.id = q.user_id
                    GROUP BY u.id, u.username, u.email, u.avatar
                    HAVING total_quizzes > 0
                    ORDER BY total_quizzes DESC
                    LIMIT 100
                """)
            elif rank_type == 'accuracy':
                # 正确率排行榜
                cursor.execute("""
                    SELECT u.id, u.username, u.email, u.avatar,
                           SUM(q.score) as total_score,
                           COUNT(q.id) as total_quizzes,
                           SUM(q.correct_count) as total_correct,
                           SUM(q.correct_count + q.wrong_count) as total_answered,
                           ROUND(SUM(q.score) * 1.0 / NULLIF(COUNT(q.id), 0), 1) as avg_score,
                           ROUND(SUM(q.correct_count) * 100.0 / NULLIF(SUM(q.correct_count + q.wrong_count), 0), 1) as accuracy
                    FROM users u
                    INNER JOIN quiz_results q ON u.id = q.user_id
                    GROUP BY u.id, u.username, u.email, u.avatar
                    HAVING total_answered > 0
                    ORDER BY accuracy DESC, total_quizzes DESC
                    LIMIT 100
                """)
            elif rank_type == 'avg':
                # 平均分排行榜
                cursor.execute("""
                    SELECT u.id, u.username, u.email, u.avatar,
                           SUM(q.score) as total_score,
                           COUNT(q.id) as total_quizzes,
                           SUM(q.correct_count) as total_correct,
                           SUM(q.correct_count + q.wrong_count) as total_answered,
                           ROUND(SUM(q.score) * 1.0 / NULLIF(COUNT(q.id), 0), 1) as avg_score,
                           ROUND(SUM(q.correct_count) * 100.0 / NULLIF(SUM(q.correct_count + q.wrong_count), 0), 1) as accuracy
                    FROM users u
                    INNER JOIN quiz_results q ON u.id = q.user_id
                    GROUP BY u.id, u.username, u.email, u.avatar
                    HAVING total_quizzes > 0
                    ORDER BY avg_score DESC
                    LIMIT 100
                """)
            else:
                conn.close()
                return jsonify({'success': False, 'message': '无效的排行榜类型'})
            
            leaderboard = []
            for row in cursor.fetchall():
                total_score = int(row.get('total_score') or 0)
                total_quizzes = int(row.get('total_quizzes') or 0)
                accuracy = float(row.get('accuracy') or 0)
                avg_score = float(row.get('avg_score', 0) or 0)

                # 根据排行榜类型计算展示用数值
                if rank_type == 'score':
                    stat_value = total_score
                    quiz_count = total_quizzes
                elif rank_type == 'quiz':
                    stat_value = total_quizzes
                    quiz_count = total_quizzes
                elif rank_type == 'avg':
                    stat_value = avg_score
                    quiz_count = total_quizzes
                else:
                    stat_value = total_score
                    quiz_count = total_quizzes

                leaderboard.append({
                    'username': row['username'],
                    'email': row['email'],
                    'avatar': row.get('avatar') or None,
                    'total_score': total_score,
                    'total_quizzes': total_quizzes,
                    'accuracy': accuracy,
                    'avg_score': avg_score,
                    'stat_value': stat_value,
                    'quiz_count': quiz_count
                })

            # 计算汇总统计数据
            total_users = len(leaderboard)
            sum_quizzes = sum(user['total_quizzes'] for user in leaderboard)
            sum_scores = sum(user['total_score'] for user in leaderboard)
            overall_avg_score = round(sum_scores / sum_quizzes, 1) if sum_quizzes > 0 else 0
            
            # 获取当前用户排名（如果已登录）
            my_rank = None
            if session.get('logged_in') and session.get('user_id'):
                user_id = session.get('user_id')
                
                # 根据类型查询当前用户排名
                if rank_type == 'score':
                    cursor.execute("""
                        SELECT 
                            (SELECT COUNT(*) + 1 FROM (
                                SELECT SUM(score) as total_score
                                FROM quiz_results
                                WHERE user_id IS NOT NULL
                                GROUP BY user_id
                                HAVING total_score > (
                                    SELECT SUM(score) FROM quiz_results WHERE user_id = %s
                                )
                            ) as ranked) as user_rank,
                            SUM(score) as total_score,
                            COUNT(*) as total_quizzes,
                            ROUND(SUM(correct_count) * 100.0 / NULLIF(SUM(correct_count + wrong_count), 0), 1) as accuracy
                        FROM quiz_results
                        WHERE user_id = %s
                    """, [user_id, user_id])
                elif rank_type == 'quiz':
                    cursor.execute("""
                        SELECT 
                            (SELECT COUNT(*) + 1 FROM (
                                SELECT COUNT(*) as total_quizzes
                                FROM quiz_results
                                WHERE user_id IS NOT NULL
                                GROUP BY user_id
                                HAVING total_quizzes > (
                                    SELECT COUNT(*) FROM quiz_results WHERE user_id = %s
                                )
                            ) as ranked) as user_rank,
                            SUM(score) as total_score,
                            COUNT(*) as total_quizzes,
                            ROUND(SUM(correct_count) * 100.0 / NULLIF(SUM(correct_count + wrong_count), 0), 1) as accuracy
                        FROM quiz_results
                        WHERE user_id = %s
                    """, [user_id, user_id])
                elif rank_type == 'accuracy':
                    cursor.execute("""
                        SELECT 
                            (SELECT COUNT(*) + 1 FROM (
                                SELECT ROUND(SUM(correct_count) * 100.0 / NULLIF(SUM(correct_count + wrong_count), 0), 1) as accuracy
                                FROM quiz_results
                                WHERE user_id IS NOT NULL
                                GROUP BY user_id
                                HAVING accuracy > (
                                    SELECT ROUND(SUM(correct_count) * 100.0 / NULLIF(SUM(correct_count + wrong_count), 0), 1)
                                    FROM quiz_results WHERE user_id = %s
                                )
                            ) as ranked) as user_rank,
                            SUM(score) as total_score,
                            COUNT(*) as total_quizzes,
                            ROUND(SUM(correct_count) * 100.0 / NULLIF(SUM(correct_count + wrong_count), 0), 1) as accuracy
                        FROM quiz_results
                        WHERE user_id = %s
                    """, [user_id, user_id])
                
                rank_row = cursor.fetchone()
                if rank_row and rank_row.get('total_quizzes', 0) > 0:
                    my_rank = {
                        'rank': int(rank_row.get('user_rank') or 0),
                        'total_score': int(rank_row.get('total_score') or 0),
                        'total_quizzes': int(rank_row.get('total_quizzes') or 0),
                        'accuracy': float(rank_row.get('accuracy') or 0)
                    }
        
        conn.close()
        
        return jsonify({
            'success': True,
            'leaderboard': leaderboard,
            'my_rank': my_rank,
            'total_users': total_users,
            'total_quizzes': sum_quizzes,
            'avg_score': overall_avg_score
        })
    except Exception as e:
        print(f"[ERROR] 获取排行榜失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取排行榜失败: {str(e)}'})


@app.route("/api/admin/categories", methods=['GET'])
def admin_categories():
    """管理员获取分类列表"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT id, name, description, icon, question_count, status
                FROM categories
                WHERE status = 'active'
                ORDER BY id
            """)
            categories = cursor.fetchall()
        
        conn.close()
        
        return jsonify({
            'success': True,
            'categories': categories
        })
    except Exception as e:
        print(f"[ERROR] 获取分类列表失败: {e}")
        return jsonify({'success': False, 'message': f'获取分类列表失败: {str(e)}'})


@app.route("/api/admin/questions", methods=['GET'])
def admin_questions():
    """管理员获取题目列表"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT q.id, q.title, q.question_type, q.question_image,
                       q.option_a, q.option_a_image,
                       q.option_b, q.option_b_image,
                       q.option_c, q.option_c_image,
                       q.option_d, q.option_d_image,
                       q.correct_answer, q.explanation, q.explanation_image,
                       q.difficulty, q.status, q.fill_in_answer, q.fill_in_keywords,
                       c.name as category_name
                FROM questions q
                LEFT JOIN categories c ON q.category_id = c.id
                ORDER BY q.id DESC
            """)
            questions = cursor.fetchall()
        
        conn.close()
        
        return jsonify({
            'success': True,
            'questions': questions
        })
    except Exception as e:
        print(f"[ERROR] 获取题目列表失败: {e}")
        return jsonify({'success': False, 'message': f'获取题目列表失败: {str(e)}'})


@app.route("/api/admin/questions", methods=['POST'])
def admin_add_question():
    """管理员添加题目"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        data = request.get_json()
        
        # 验证必填项
        category_id = data.get('category_id')
        title = data.get('title', '').strip()
        question_type = data.get('question_type', 'multiple_choice')
        
        if not category_id or not title:
            return jsonify({'success': False, 'message': '请填写所有必填项'})
        
        # 根据题目类型验证不同的必填项
        if question_type == 'fill_in_blank':
            fill_in_answer = data.get('fill_in_answer', '')
            if fill_in_answer:
                fill_in_answer = fill_in_answer.strip()
            if not fill_in_answer:
                return jsonify({'success': False, 'message': '请填写填空题答案'})
            
            fill_in_keywords = data.get('fill_in_keywords', '')
            if fill_in_keywords:
                fill_in_keywords = fill_in_keywords.strip()
            else:
                fill_in_keywords = None  # 关键词为空时设为None
                
            correct_answer = fill_in_answer  # 填空题的正确答案就是填空答案
            option_a = option_b = ''  # 填空题不需要选项，但数据库字段不允许NULL，设为空字符串
            option_c = option_d = None  # 这两个字段允许为NULL
        else:
            option_a = data.get('option_a', '').strip()
            option_b = data.get('option_b', '').strip()
            correct_answer = data.get('correct_answer')
            
            if not option_a or not option_b or not correct_answer:
                return jsonify({'success': False, 'message': '请填写所有必填项'})
            
            # 验证正确答案必须是 A、B、C 或 D
            if correct_answer not in ['A', 'B', 'C', 'D']:
                return jsonify({'success': False, 'message': '正确答案必须是 A、B、C 或 D'})
            
            fill_in_answer = fill_in_keywords = None  # 选择题不需要填空字段
        
        option_c = data.get('option_c')
        if option_c:
            option_c = option_c.strip()
        else:
            option_c = None
            
        option_d = data.get('option_d')
        if option_d:
            option_d = option_d.strip()
        else:
            option_d = None
            
        explanation = data.get('explanation', '')
        if explanation:
            explanation = explanation.strip()
        else:
            explanation = ''
        difficulty = data.get('difficulty', 'medium')
        
        # 获取图片字段（处理None和空字符串）
        question_image = data.get('question_image')
        question_image = question_image.strip() if question_image else None
        
        option_a_image = data.get('option_a_image')
        option_a_image = option_a_image.strip() if option_a_image else None
        
        option_b_image = data.get('option_b_image')
        option_b_image = option_b_image.strip() if option_b_image else None
        
        option_c_image = data.get('option_c_image')
        option_c_image = option_c_image.strip() if option_c_image else None
        
        option_d_image = data.get('option_d_image')
        option_d_image = option_d_image.strip() if option_d_image else None
        
        explanation_image = data.get('explanation_image')
        explanation_image = explanation_image.strip() if explanation_image else None
        
        # 验证难度
        if difficulty not in ['easy', 'medium', 'hard']:
            difficulty = 'medium'
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor() as cursor:
            # 验证分类是否存在
            cursor.execute("SELECT id FROM categories WHERE id = %s", [category_id])
            if not cursor.fetchone():
                conn.close()
                return jsonify({'success': False, 'message': '所选分类不存在'})
            
            # 插入新题目
            cursor.execute("""
                INSERT INTO questions 
                (category_id, title, question_type, question_image, option_a, option_a_image, option_b, option_b_image, 
                 option_c, option_c_image, option_d, option_d_image, correct_answer, explanation, 
                 explanation_image, difficulty, fill_in_answer, fill_in_keywords, status)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'active')
            """, [
                category_id, title, question_type, question_image, option_a, option_a_image, option_b, option_b_image,
                option_c, option_c_image, option_d, option_d_image, correct_answer, explanation,
                explanation_image, difficulty, fill_in_answer, fill_in_keywords
            ])
            
            # 更新分类的题目数量
            cursor.execute("""
                UPDATE categories 
                SET question_count = (SELECT COUNT(*) FROM questions WHERE category_id = %s AND status = 'active')
                WHERE id = %s
            """, [category_id, category_id])
            
            conn.commit()
        
        conn.close()
        
        print(f"[OK] 管理员添加了新题目: {title[:50]}...")
        return jsonify({'success': True, 'message': '题目添加成功'})
        
    except Exception as e:
        print(f"[ERROR] 添加题目失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'添加题目失败: {str(e)}'})


@app.route("/api/admin/questions/<int:question_id>", methods=['DELETE'])
def admin_delete_question(question_id):
    """管理员删除题目"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor() as cursor:
            # 检查题目是否存在
            cursor.execute("SELECT id, category_id FROM questions WHERE id = %s", [question_id])
            question = cursor.fetchone()
            
            if not question:
                conn.close()
                return jsonify({'success': False, 'message': '题目不存在'})
            
            category_id = question[1]
            
            # 删除题目（或标记为 inactive）
            cursor.execute("DELETE FROM questions WHERE id = %s", [question_id])
            
            # 更新分类的题目数量
            if category_id:
                cursor.execute("""
                    UPDATE categories 
                    SET question_count = (SELECT COUNT(*) FROM questions WHERE category_id = %s AND status = 'active')
                    WHERE id = %s
                """, [category_id, category_id])
            
            conn.commit()
        
        conn.close()
        
        print(f"[OK] 管理员删除了题目 ID: {question_id}")
        return jsonify({'success': True, 'message': '题目删除成功'})
        
    except Exception as e:
        print(f"[ERROR] 删除题目失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'删除题目失败: {str(e)}'})


@app.route("/api/admin/questions/batch", methods=['POST'])
def admin_batch_add_questions():
    """管理员批量添加题目"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        data = request.get_json()
        questions = data.get('questions', [])
        
        if not questions or not isinstance(questions, list):
            return jsonify({'success': False, 'message': '请提供题目数组'})
        
        if len(questions) == 0:
            return jsonify({'success': False, 'message': '题目列表为空'})
        
        if len(questions) > 1000:
            return jsonify({'success': False, 'message': '单次最多插入1000道题目'})
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        success_count = 0
        error_count = 0
        errors = []
        
        with conn.cursor() as cursor:
            for idx, q in enumerate(questions):
                try:
                    # 验证必填项
                    category_id = q.get('category_id')
                    title = q.get('title', '').strip()
                    option_a = q.get('option_a', '').strip()
                    option_b = q.get('option_b', '').strip()
                    correct_answer = q.get('correct_answer')
                    
                    if not category_id or not title or not option_a or not option_b or not correct_answer:
                        errors.append(f"第{idx+1}题: 缺少必填项")
                        error_count += 1
                        continue
                    
                    # 验证正确答案
                    if correct_answer not in ['A', 'B', 'C', 'D']:
                        errors.append(f"第{idx+1}题: 正确答案必须是 A、B、C 或 D")
                        error_count += 1
                        continue
                    
                    option_c = q.get('option_c', '').strip() if q.get('option_c') else None
                    option_d = q.get('option_d', '').strip() if q.get('option_d') else None
                    explanation = q.get('explanation', '').strip()
                    difficulty = q.get('difficulty', 'medium')
                    
                    # 验证难度
                    if difficulty not in ['easy', 'medium', 'hard']:
                        difficulty = 'medium'
                    
                    # 插入题目
                    cursor.execute("""
                        INSERT INTO questions 
                        (category_id, title, option_a, option_b, option_c, option_d, 
                         correct_answer, explanation, difficulty, status)
                        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'active')
                    """, [
                        category_id, title, option_a, option_b, option_c, option_d,
                        correct_answer, explanation, difficulty
                    ])
                    
                    success_count += 1
                    
                except Exception as e:
                    errors.append(f"第{idx+1}题: {str(e)}")
                    error_count += 1
            
            # 更新所有涉及分类的题目数量
            cursor.execute("""
                UPDATE categories c
                SET question_count = (
                    SELECT COUNT(*) FROM questions 
                    WHERE category_id = c.id AND status = 'active'
                )
            """)
            
            conn.commit()
        
        conn.close()
        
        message = f"批量添加完成: 成功{success_count}道，失败{error_count}道"
        print(f"[OK] {message}")
        
        return jsonify({
            'success': True,
            'message': message,
            'success_count': success_count,
            'error_count': error_count,
            'errors': errors[:10]  # 只返回前10个错误
        })
        
    except Exception as e:
        print(f"[ERROR] 批量添加题目失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'批量添加失败: {str(e)}'})


@app.route("/api/admin/questions/import-json", methods=['POST'])
def admin_import_json():
    """从JSON文件导入题目"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        # 检查是否上传了文件
        if 'file' not in request.files:
            return jsonify({'success': False, 'message': '未上传文件'})
        
        file = request.files['file']
        
        if file.filename == '':
            return jsonify({'success': False, 'message': '未选择文件'})
        
        if not file.filename.endswith('.json'):
            return jsonify({'success': False, 'message': '只支持JSON文件'})
        
        # 读取JSON内容
        content = file.read().decode('utf-8')
        data = json.loads(content)
        
        questions = data.get('questions', [])
        
        if not questions:
            return jsonify({'success': False, 'message': 'JSON文件中没有找到题目数组'})
        
        # 调用批量插入逻辑
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        success_count = 0
        error_count = 0
        errors = []
        
        with conn.cursor() as cursor:
            for idx, q in enumerate(questions):
                try:
                    category_id = q.get('category_id')
                    title = q.get('title', '').strip()
                    option_a = q.get('option_a', '').strip()
                    option_b = q.get('option_b', '').strip()
                    correct_answer = q.get('correct_answer')
                    
                    if not category_id or not title or not option_a or not option_b or not correct_answer:
                        errors.append(f"第{idx+1}题: 缺少必填项")
                        error_count += 1
                        continue
                    
                    if correct_answer not in ['A', 'B', 'C', 'D']:
                        errors.append(f"第{idx+1}题: 正确答案格式错误")
                        error_count += 1
                        continue
                    
                    option_c = q.get('option_c', '').strip() if q.get('option_c') else None
                    option_d = q.get('option_d', '').strip() if q.get('option_d') else None
                    explanation = q.get('explanation', '').strip()
                    difficulty = q.get('difficulty', 'medium')
                    
                    if difficulty not in ['easy', 'medium', 'hard']:
                        difficulty = 'medium'
                    
                    cursor.execute("""
                        INSERT INTO questions 
                        (category_id, title, option_a, option_b, option_c, option_d, 
                         correct_answer, explanation, difficulty, status)
                        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'active')
                    """, [
                        category_id, title, option_a, option_b, option_c, option_d,
                        correct_answer, explanation, difficulty
                    ])
                    
                    success_count += 1
                    
                except Exception as e:
                    errors.append(f"第{idx+1}题: {str(e)}")
                    error_count += 1
            
            # 更新分类题目数量
            cursor.execute("""
                UPDATE categories c
                SET question_count = (
                    SELECT COUNT(*) FROM questions 
                    WHERE category_id = c.id AND status = 'active'
                )
            """)
            
            conn.commit()
        
        conn.close()
        
        message = f"导入完成: 成功{success_count}道，失败{error_count}道"
        print(f"[OK] {message}")
        
        return jsonify({
            'success': True,
            'message': message,
            'success_count': success_count,
            'error_count': error_count,
            'errors': errors[:10]
        })
        
    except json.JSONDecodeError:
        return jsonify({'success': False, 'message': 'JSON格式错误'})
    except Exception as e:
        print(f"[ERROR] 导入JSON失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'导入失败: {str(e)}'})


@app.route("/api/admin/upload-image", methods=['POST'])
def admin_upload_image():
    """管理员上传题目图片"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    if 'image' not in request.files:
        return jsonify({'success': False, 'message': '没有上传文件'})
    
    file = request.files['image']
    
    if file.filename == '':
        return jsonify({'success': False, 'message': '未选择文件'})
    
    if file and allowed_file(file.filename):
        try:
            # 生成唯一文件名
            ext = file.filename.rsplit('.', 1)[1].lower()
            filename = f"{uuid.uuid4().hex}.{ext}"
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            
            # 确保目录存在
            os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
            
            # 保存文件
            file.save(filepath)
            
            # 返回相对路径（用于存储到数据库）
            relative_path = f"/static/uploads/questions/{filename}"
            
            return jsonify({
                'success': True,
                'message': '上传成功',
                'image_url': relative_path
            })
        except Exception as e:
            print(f"[ERROR] 上传图片失败: {e}")
            return jsonify({'success': False, 'message': f'上传失败: {str(e)}'})
    else:
        return jsonify({'success': False, 'message': '不支持的文件格式，请上传图片文件（png, jpg, jpeg, gif, webp）'})


@app.route("/api/admin/delete-image", methods=['POST'])
def admin_delete_image():
    """管理员删除图片"""
    if not session.get('admin_logged_in'):
        return jsonify({'success': False, 'message': '请先登录'})
    
    try:
        data = request.get_json()
        image_url = data.get('image_url', '')
        
        if not image_url:
            return jsonify({'success': False, 'message': '图片路径不能为空'})
        
        # 提取文件名
        if image_url.startswith('/static/uploads/questions/'):
            filename = image_url.replace('/static/uploads/questions/', '')
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            
            # 删除文件
            if os.path.exists(filepath):
                os.remove(filepath)
                return jsonify({'success': True, 'message': '删除成功'})
            else:
                return jsonify({'success': False, 'message': '文件不存在'})
        else:
            return jsonify({'success': False, 'message': '无效的图片路径'})
            
    except Exception as e:
        print(f"[ERROR] 删除图片失败: {e}")
        return jsonify({'success': False, 'message': f'删除失败: {str(e)}'})


# ========== AI助手功能 ==========
# DeepSeek AI API配置
DEEPSEEK_API_KEY = "sk-e93b780b1fa34f80a1cd4f84c24dc908"  # 请替换为你的DeepSeek API Key
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"

# Kimi AI API配置
KIMI_API_KEY = "sk-aj5XhJbBJ6KqOztYGlMTCxV3S8UopjA2vh6SQi85FIEVWfj9"  # 请替换为你的Kimi API Key
KIMI_API_URL = "https://api.moonshot.cn/v1/chat/completions"

# 默认使用的AI服务
DEFAULT_AI_SERVICE = "deepseek"  # 可选: "deepseek" 或 "kimi"

@app.route("/api/ai/chat", methods=['POST'])
def ai_chat():
    """AI助手对话接口（流式输出，支持多个AI服务）"""
    try:
        data = request.get_json()
        user_message = data.get('message', '').strip()
        ai_service = data.get('service', DEFAULT_AI_SERVICE).lower()  # 获取AI服务选择
        
        if not user_message:
            return jsonify({'success': False, 'message': '消息不能为空'})
        
        # 验证AI服务选择
        if ai_service not in ['deepseek', 'kimi']:
            ai_service = DEFAULT_AI_SERVICE
        
        # 构建对话上下文
        messages = [
            {
                "role": "system",
                "content": "你是一个友好的AI助手，专门帮助用户解答问题。请用简洁、清晰的语言回答，如果是学习相关的问题，请给出详细的解释和提示，但不要直接给出答案，而是引导用户思考。\n\n重要提示：\n1. 当回答涉及数学公式时，请使用LaTeX格式，用$包围行内公式，用$$包围块级公式\n2. 例如：行内公式 $x^2 + y^2 = z^2$，块级公式：\n$$\\int_{0}^{\\infty} e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}$$\n3. 支持的LaTeX语法包括：分数 \\frac{a}{b}、上标 x^2、下标 x_1、根号 \\sqrt{x}、积分 \\int、求和 \\sum、希腊字母 \\alpha \\beta \\gamma 等\n4. 请确保LaTeX语法正确，这样用户就能看到美观的数学公式"
            },
            {
                "role": "user",
                "content": user_message
            }
        ]
        
        # 根据选择的服务获取配置
        if ai_service == 'kimi':
            api_key = KIMI_API_KEY
            api_url = KIMI_API_URL
            model_name = "moonshot-v1-8k"
            service_display_name = "Kimi"
        else:  # deepseek
            api_key = DEEPSEEK_API_KEY
            api_url = DEEPSEEK_API_URL
            model_name = "deepseek-chat"
            service_display_name = "DeepSeek"
        
        # 如果API Key未配置，返回模拟流式响应
        if api_key == "your-kimi-api-key-here" or api_key == "your-deepseek-api-key-here":
            def generate_mock_stream():
                if ai_service == 'kimi':
                    guide_text = '请在 hello.py 中配置 KIMI_API_KEY 以使用真实的Kimi AI功能。\n\n配置方法：\n1. 访问 https://platform.moonshot.cn/ 注册账号\n2. 获取API Key\n3. 在 hello.py 中将 KIMI_API_KEY 替换为你的真实API Key'
                else:
                    guide_text = '请在 hello.py 中配置 DEEPSEEK_API_KEY 以使用真实的DeepSeek AI功能。\n\n配置方法：\n1. 访问 https://platform.deepseek.com/ 注册账号\n2. 获取API Key\n3. 在 hello.py 中将 DEEPSEEK_API_KEY 替换为你的真实API Key'
                
                mock_message = f'这是一个模拟回复（当前选择：{service_display_name}）。你的问题是："{user_message}"\n\n{guide_text}'
                # 模拟流式输出
                import time
                for char in mock_message:
                    yield f"data: {json.dumps({'content': char})}\n\n"
                    time.sleep(0.01)  # 模拟打字效果
                yield "data: [DONE]\n\n"
            
            return app.response_class(
                generate_mock_stream(),
                mimetype='text/event-stream',
                headers={
                    'Cache-Control': 'no-cache',
                    'X-Accel-Buffering': 'no'
                }
            )
        
        # 调用AI API（流式）
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }
        
        payload = {
            "model": model_name,
            "messages": messages,
            "temperature": 0.7,
            "max_tokens": 1000,
            "stream": True  # 启用流式输出
        }
        
        print(f"[AI] 使用服务: {service_display_name} ({ai_service})")
        print(f"[AI] 模型: {model_name}")
        
        def generate():
            try:
                response = requests.post(
                    api_url,
                    headers=headers,
                    json=payload,
                    timeout=60,
                    stream=True
                )
                
                if response.status_code == 200:
                    print(f"[AI] 用户: {user_message}")
                    print(f"[AI] 开始流式回复...")
                    
                    for line in response.iter_lines():
                        if line:
                            line = line.decode('utf-8')
                            if line.startswith('data: '):
                                data_str = line[6:]  # 去掉 'data: ' 前缀
                                if data_str == '[DONE]':
                                    yield "data: [DONE]\n\n"
                                    break
                                try:
                                    chunk = json.loads(data_str)
                                    if 'choices' in chunk and len(chunk['choices']) > 0:
                                        delta = chunk['choices'][0].get('delta', {})
                                        content = delta.get('content', '')
                                        if content:
                                            yield f"data: {json.dumps({'content': content})}\n\n"
                                except json.JSONDecodeError:
                                    continue
                else:
                    error_msg = f"API调用失败: {response.status_code}"
                    print(f"[ERROR] {error_msg}")
                    yield f"data: {json.dumps({'error': error_msg})}\n\n"
                    yield "data: [DONE]\n\n"
                    
            except requests.exceptions.Timeout:
                print("[ERROR] AI API请求超时")
                yield f"data: {json.dumps({'error': 'AI响应超时，请重试'})}\n\n"
                yield "data: [DONE]\n\n"
            except Exception as e:
                print(f"[ERROR] AI流式输出失败: {e}")
                import traceback
                traceback.print_exc()
                yield f"data: {json.dumps({'error': str(e)})}\n\n"
                yield "data: [DONE]\n\n"
        
        return app.response_class(
            generate(),
            mimetype='text/event-stream',
            headers={
                'Cache-Control': 'no-cache',
                'X-Accel-Buffering': 'no'
            }
        )
            
    except Exception as e:
        print(f"[ERROR] AI对话失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'AI服务异常: {str(e)}'})

# ===================================

# ========== Tack表管理API ==========
@app.route("/api/tack/config", methods=['GET'])
def get_tack_config():
    """获取tack配置 - 用于定时执行程序"""
    if not USE_DATABASE:
        return jsonify({'times': 10, 'interval': 1, 'state': 'open'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'times': 10, 'interval': 1, 'state': 'open'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取第一条记录作为配置（如果有多条，可以根据需要修改逻辑）
            cursor.execute("SELECT times, intervals, state, pc_state FROM tack LIMIT 1")
            data = cursor.fetchone()
        
        conn.close()
        
        if not data:
            # 如果没有数据，返回默认配置
            return jsonify({'times': 10, 'interval': 1, 'state': 'open'})
        
        # 返回指定格式的数据
        return jsonify({
            'times': int(data['times']),
            'interval': int(data['intervals']),
            'state': str(data['state']),
            'pc_state': str(data.get('pc_state', 'run'))
        })
    except Exception as e:
        print(f"[ERROR] 获取tack配置失败: {e}")
        import traceback
        traceback.print_exc()
        # 出错时返回默认配置
        return jsonify({'times': 10, 'interval': 1, 'state': 'open', 'pc_state': 'run'})


@app.route("/api/test/tack", methods=['GET'])
def get_tack_list():
    """获取tack表所有数据"""
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("SELECT times, intervals, state, pc_state FROM tack")
            data = cursor.fetchall()
        
        conn.close()
        
        return jsonify({
            'success': True,
            'data': data
        })
    except Exception as e:
        print(f"[ERROR] 获取tack数据失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'获取数据失败: {str(e)}'})


@app.route("/api/test/tack/first", methods=['GET'])
def get_tack_first():
    """获取第一条tack记录"""
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("SELECT times, intervals, state, pc_state FROM tack LIMIT 1")
            data = cursor.fetchone()
        
        conn.close()
        
        if not data:
            return jsonify({'success': False, 'message': '记录不存在'})
        
        return jsonify({
            'success': True,
            'data': data
        })
    except Exception as e:
        print(f"[ERROR] 获取tack记录失败: {e}")
        return jsonify({'success': False, 'message': f'获取记录失败: {str(e)}'})


@app.route("/api/test/tack", methods=['POST'])
def create_tack():
    """创建新的tack记录（如果表为空）或更新现有记录"""
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({'success': False, 'message': '无效的请求数据'})
        
        times = data.get('times')
        intervals = data.get('intervals')
        state = data.get('state')
        pc_state = data.get('pc_state', 'run')  # 默认值为run
        
        # 验证数据
        if times is None or intervals is None or not state:
            return jsonify({'success': False, 'message': '请填写所有必填字段'})
        
        if state not in ['open', 'closed']:
            return jsonify({'success': False, 'message': 'state字段必须是open或closed'})
        
        # 验证pc_state值
        if pc_state not in ['run', 'stop']:
            return jsonify({'success': False, 'message': 'pc_state必须是run或stop'})
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor() as cursor:
            # 检查表中是否已有数据
            cursor.execute("SELECT COUNT(*) FROM tack")
            count = cursor.fetchone()[0]
            
            if count > 0:
                # 如果已有数据，更新第一条记录
                cursor.execute("""
                    UPDATE tack 
                    SET times = %s, intervals = %s, state = %s, pc_state = %s
                    LIMIT 1
                """, [times, intervals, state, pc_state])
                message = '更新成功'
            else:
                # 如果没有数据，插入新记录
                cursor.execute("""
                    INSERT INTO tack (times, intervals, state, pc_state)
                    VALUES (%s, %s, %s, %s)
                """, [times, intervals, state, pc_state])
                message = '创建成功'
        
        conn.commit()
        conn.close()
        
        print(f"[OK] {message}")
        return jsonify({
            'success': True,
            'message': message
        })
    except Exception as e:
        print(f"[ERROR] 操作tack记录失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'操作失败: {str(e)}'})


@app.route("/api/test/tack/update", methods=['PUT'])
def update_tack():
    """更新tack记录（更新第一条记录）"""
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({'success': False, 'message': '无效的请求数据'})
        
        times = data.get('times')
        intervals = data.get('intervals')
        state = data.get('state')
        pc_state = data.get('pc_state', 'run')  # 默认值为run
        
        # 验证数据
        if times is None or intervals is None or not state:
            return jsonify({'success': False, 'message': '请填写所有必填字段'})
        
        if state not in ['open', 'closed']:
            return jsonify({'success': False, 'message': 'state字段必须是open或closed'})
        
        # 验证pc_state值
        if pc_state not in ['run', 'stop']:
            return jsonify({'success': False, 'message': 'pc_state必须是run或stop'})
        
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor() as cursor:
            # 检查是否有记录
            cursor.execute("SELECT COUNT(*) FROM tack")
            if cursor.fetchone()[0] == 0:
                conn.close()
                return jsonify({'success': False, 'message': '没有记录可更新'})
            
            # 更新第一条记录
            cursor.execute("""
                UPDATE tack 
                SET times = %s, intervals = %s, state = %s, pc_state = %s
                LIMIT 1
            """, [times, intervals, state, pc_state])
        
        conn.commit()
        conn.close()
        
        print(f"[OK] 更新tack记录成功")
        return jsonify({
            'success': True,
            'message': '更新成功'
        })
    except Exception as e:
        print(f"[ERROR] 更新tack记录失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'更新失败: {str(e)}'})


@app.route("/api/test/tack/clear", methods=['DELETE'])
def clear_tack():
    """清空tack表所有记录"""
    if not USE_DATABASE:
        return jsonify({'success': False, 'message': '数据库未启用'})
    
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({'success': False, 'message': '数据库连接失败'})
        
        with conn.cursor() as cursor:
            # 删除所有记录
            cursor.execute("DELETE FROM tack")
        
        conn.commit()
        conn.close()
        
        print(f"[OK] 清空tack表成功")
        return jsonify({
            'success': True,
            'message': '清空成功'
        })
    except Exception as e:
        print(f"[ERROR] 清空tack表失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': f'清空失败: {str(e)}'})

# ===================================

if __name__ == '__main__':
    # 开发环境配置
    # 生产环境请使用 Gunicorn 等 WSGI 服务器运行
    app.run(
        host='0.0.0.0',  # 允许外部访问
        port=5000,       # 端口号
        debug=False      # 生产环境必须设置为 False
    )